import moment from 'moment';
import store from "@/store";

/**
 * 将Long类型时间转换
 * @param dateString
 * @returns {{length}|string|string}
 */
export const formatDateLong = (dateString) => {
  if (dateString === undefined || dateString === null || dateString === '') {
    return '';
  }
  dateString = dateString + '';
  if (!dateString.length) {
    return '';
  } else if (dateString.length == 6) {
    return dateString.substring(0, 4) + "-" + dateString.substring(4, 6);
  } else if (dateString.length == 8) {
    return dateString.substring(0, 4) + "-" + dateString.substring(4, 6) + "-" + dateString.substring(6, 8);
  } else if (dateString.length == 14) {
    return dateString.substring(0, 4) + "-" + dateString.substring(4, 6) + "-" + dateString.substring(6, 8) + " " + dateString.substring(8, 10) + ":" + dateString.substring(10, 12) + ":" + dateString.substring(12, 14);
  } else if (dateString.length == 13) {
    let date = new Date();
    date.setTime(dateString);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  } else {
    return dateString;
  }
}

/**
 * 地区码转地区名
 * @param address
 * @returns {null|*}
 */
export const filterAddress = (address) => {
  let data = store.getters.allDistrict;
  return (data[address]) ? data[address] : address;
};

export const dateFormat = (date) => {
  return date ? moment(date).format('YYYY-MM-DD') : ''
}

//因为后台返回的时间格式不规范，有时是时间的数字，有时是标准模式，所以要做foramt兼容
export const dateTimeFormat = (date) => {
  let obj = null;
  if (isNaN(date) === false && date.toString().length === 14) {
    const regDate = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/;
    obj = ('' + date).replace(regDate, "$1-$2-$3 $4:$5:$6");
  } else {
    obj = moment(date).format('YYYY-MM-DD HH:mm:ss');
  }
  return date ? obj : ''
}

/**
 * 隐藏手机号码
 * @param val {Number, String} 转换的字符串对象
 * @param retain {Number} 保留位数
 * @return {String}
 */
export const privatePhone = function (val, retain = 4) {
  if (!NUMBER(val) || String(val).length !== 11 || retain == 0) return val;
  let phone = String(val)
  let digit = 11 - 3 - retain
  let reg = new RegExp(`^(\\d{3})\\d{${digit}}(\\d{${retain}})$`)
  return mobile.replace(reg, `$1${'*'.repeat(digit)}$2`)
}
